<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * User CRUD model class 
 */
Class User_model extends CI_Model {

    public $users_table;
    public $usermeta_table;

    /**
     * Constructor adds prefix to $this table name
     * Loads default user exceptions
     */
    function __construct() {
        // Call the Model constructor
        parent::__construct();

        // prefix table names
        $this->users_table = $this->db->dbprefix('users');

        // load requed exception libraries
        $this->load->library("exceptions/insufficient_parameters_exception");
        $this->load->library("exceptions/not_exists_exception");
        $this->load->library("exceptions/user_already_exists_exception");
        $this->load->library("exceptions/user_login_error_exception");
    }

    /**
     * Checks login validity
     * 
     * **** NO EXCEPTION THROWN ****
     *  
     * @param type $username
     * @param type $password
     * @return type 
     */
    function login_check($user_login, $user_pass) {
        $this->db->select('*');
        $this->db->from($this->users_table);
        $this->db->where('user_login', $user_login);
        $this->db->where('user_pass', md5($user_pass));
        $this->db->limit(1);

        $query = $this->db->get();
		
        if ($query->num_rows() == 1) {
            $result = $query->result();
            return $result[0];
        } else {
            throw new user_login_error_exception("Hibás felhasználónév/jelszó");
        }
    }

    /**
     * 
     * Add new user
     * 
     * @param type $user_data
     * @param type $usermeta_data 
     */
    function add_user($user_data = array()) {
        // use md5 on user pass, and user registered time
        $user_data['user_registered'] = date('Y-m-d H:i:s');
        $user_data['user_pass'] = md5($user_data['user_pass']);

        // insert user_data
        $this->db->insert($this->users_table, $user_data);
    }

    /**
     * Gives back user by id 
     * 
     * @param type $id
     * @return array (user_id, username, user)
     */
    function get_user($id) {
        // constructing active record query
        $query = $this->db->get_where($this->users_table, array('user_id' => $id));
        // do the query
        $result = $query->result();
        if ($result == NULL)
            return NULL;
        return $result[0];
    }

    /**
     * 
     * 
     * 
     * Update user by id.
     * saves usermeta if given.
     * 
     * 
     * @return true on success
     */
    function update_user($user_data = array()) {
        // if user does not exists throw user_not_exists_exception
        if ($this->get_user($user_data['user_id']) == FALSE)
            throw new not_exists_exception("felhasználó");

        // if there is a password use md5 on it!
        if (isset($user_data['user_pass']))
            $user_data['user_pass'] = md5($user_data['user_pass']);

        // do selection and update data
        $this->db->where('user_id', $user_data['user_id']);
        $this->db->update($this->users_table, $user_data);
    }

    /**
     * 
     * 
     * 
     * Delete user
     * 
     * 
     * 
     * @param type $id
     * @return true on success
     */
    function delete($user_id) {
        // delete user data from users_table
        $this->db->where('user_id', $user_id);
        $this->db->delete($this->users_table);
    }

    /**
     * 
     * returns the users (for pagination)
     * 
     * options:
     *  select 
     *  search
     *  order_by
     *  order_dir
     *  limit
     *  offset
     * 
     * @param type $limit the number of returned users
     * @param type $offset from this number.
     * @return type 
     */
    function get_users($options = array()) {

        if (isset($options['select'])) {
            $this->db->select($options['select']);
        }

        if (isset($options['search_like'])) {
            $this->db->like('user_login', $options['search_like']);
            $this->db->or_like('user_email', $options['search_like']);
            $this->db->or_like('user_registered', $options['search_like']);
            $this->db->or_like('display_name', $options['search_like']);
            $this->db->or_like('real_name', $options['search_like']);
        }

        if (isset($options['limit']) && isset($options['offset']))
            $this->db->limit($options['limit'], $options['offset']);

        if (isset($options['order_by'])) {
            if (isset($options['order_dir'])) {
                $this->db->order_by($options['order_by'], $options['order_dir']);
            } else {
                $this->db->order_by($options['order_by']);
            }
        }

        $query = $this->db->get($this->users_table);


        return $query->result();
    }

    /**
     * 
     * Returns the number of users
     * 
     * 
     * @return type 
     */
    function count() {
        return $this->db->count_all_results($this->users_table);
    }

    /**
     * 
     * 
     * Checks if record is available for registration
     * if no results from got from query the username is available.
     * 
     * 
     * @param type $user_login 
     */
    function is_available($row_name, $record, $reg_id = NULL) {
        // Active Record query
        $this->db->select('user_id');
        $this->db->where($row_name, $record);
        if (isset($reg_id)) {
            $this->db->where('user_id !=', $reg_id);
        }
        $this->db->limit(1);
        $query = $this->db->get($this->users_table);
        
        if ($query->num_rows() == 0) {
            // username is available
            return true;
        } else {
            // username not available
            return false;
        }
    }


    /**
     * 
     * 
     * Returns the id of the user, or false if no such user
     * 
     * 
     * @param type $username 
     */
    function get_user_id($user_login) {
        // Active Record query
        $this->db->select('user_id');
        $this->db->where('user_login', $user_login);
        $this->db->limit(1);
        $query = $this->db->get($this->users_table);

        if ($query->num_rows() == 1) {
            $row = $query->row();
            return $row->id;
        } else {
            return false;
        }
    }

}

